﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Quickly.Spa.Shared;
using System.Diagnostics.CodeAnalysis;

namespace Quickly.SpaProxy;

public static class SpaProxyBuilderExtensions
{
    public static IServiceCollection AddSpaProxyServices(this IServiceCollection services)
    {
        // spa proxy config file 
        var spaProxyConfigFile = Path.Combine(AppContext.BaseDirectory, "quickly.spa.proxy.json");

        if (File.Exists(spaProxyConfigFile))
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile(spaProxyConfigFile)
                .Build();

            // spa proxy lanuch manager
            services.AddSingleton<SpaProxyLaunchManager>();

            // spa development server options
            ConfigureOptions<SpaDevelopmentServerOptions>(services, configuration.GetSection("SpaProxyServer"));

            // spa proxy startup fileter DI
            services.TryAddEnumerable(ServiceDescriptor.Singleton<IStartupFilter, SpaProxyStartupFilter>());
        }

        return services;
    }

    [UnconditionalSuppressMessageAttribute("Trimming", "IL2026", Justification = "Configuration object's public properties are preserved.")]
    static void ConfigureOptions<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>(IServiceCollection services, IConfigurationSection section)
        where T : class
    {
        services.Configure<T>(section);
    }

    public static IApplicationBuilder UseSpaProxyDevelopmentReverseProxy(this WebApplication app)
    {
        if (app.Services.GetServices<IStartupFilter>().Any(x => x.GetType() == typeof(SpaProxyStartupFilter)))
        {
            app.MapReverseProxy();
        }

        return app;
    }
}
